import store from './store'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken,getUserInfo } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'
// import {RouteRoleList, constantRoutes} from "./router/dict";

import { constantRoutes} from "./router/index";
import router from './router'
import Router from 'vue-router'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

//@update 修复了切换身份登录时候 出现路由重复的问题
// router.$addRoutes = (params) => {
//   router.matcher = new Router({}).matcher;
//   router.addRoutes(params);
//   router.options.routes = params;
// }

router.beforeEach( async (to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()

  if (hasToken) {
    const userInfo = getUserInfo();
    //如果登录了 则加载动态路由
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/'})  // /
      NProgress.done()
    } else if (to.path == '/index' && from.path == '/login') {
      //这里是用户刚刚登录 需要刷新router
      // const current_add_routers = userInfo.school_id == 0 ? RouteRoleList.superAdmin : RouteRoleList.schoolAdmin;
      // let new_router_options = constantRoutes.concat(current_add_routers);
      // router.$addRoutes(new_router_options);
      //router.options.routes = new_router_options;
      next();
    } else {
      next();
    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      //next(`/login?redirect=${to.path}`)
      next({path: '/login'});
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
